<template>
  <div class="wrapper">
    <!-- 登录对话框 -->
    <div class="login-box">
      <el-row>
        <el-col :span="12">
          <div
            class="grid-content bg-purple item"
            :class="state.login_type ? 'active' : ''"
            @click="tab(true)"
          >
            企业微信登录
          </div>
        </el-col>
        <el-col :span="12">
          <div
            class="grid-content bg-purple-light item"
            :class="state.login_type ? '' : 'active'"
            @click="tab(false)"
          >
            短信登录
          </div>
        </el-col>
      </el-row>
      <!-- 企业微信二维码 -->
      <img v-if="state.login_type" src="" class="wx_code" />
      <!-- 短信登录 -->
      <div v-else>
        <el-form
          :model="state.ruleForm"
          status-icon
          :rules="state.rules"
          ref="form"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="手机号" prop="phone">
            <el-input
              type="text"
              v-model="state.ruleForm.phone"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码">
            <el-col :span="10">
              <el-form-item prop="code">
                <el-input
                  type="text"
                  v-model="state.ruleForm.code"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2">&nbsp;</el-col>
            <el-col :span="4">
              <el-button
                class="getCode_btn"
                type="primary"
                :disabled="state.btn_status"
                @click="getCode"
                >{{ state.num }}</el-button
              >
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="black-box" v-if="state.blackbox"></div>
    <!-- 短信登录所需滑块 -->
    <div class="slideDiv" id="slideDiv" v-show="state.slide_dialogVisible">
      <div class="showtip"></div>
      <div class="closeSlide" @click="close_black">&times;</div>
      <div class="box" id="box">
        <img class="main1" :src="state.slide_bg" alt="" srcset="" />
        <span id="spanEle1" class="spanEle1"
          ><img class="main2" :src="state.square_url"
        /></span>
        <i class="el-icon-refresh-right refreshBtn" @click="getCode"></i>
      </div>
      <div class="btn">
        <div class="process" id="process"></div>
        向右拖动滑块填充拼图
        <div @mousedown="mousedown" class="slideSquare" id="slideHand">→</div>
      </div>
    </div>
  </div>
</template>

<script>
import { useRouter } from "vue-router";
import { ref, onMounted, reactive, getCurrentInstance } from "vue";
import { ElNotification } from "element-plus";
import { useStore } from "vuex";
export default {
  components: {},
  props: {},
  setup() {
    const { ctx } = getCurrentInstance();
    const store = useStore();
    const router = useRouter();
    let form = ref(null);
    let box = ref(null);
    let square = ref(null);
    const state = reactive({
      blackbox: false,
      login_type: true,
      ifBool: false, //判断鼠标是否按下
      slide_dialogVisible: false,
      num: "获取验证码",
      stu: false,
      btn_status: false,
      ruleForm: {
        phone: "18222963475",
        code: "",
      },
      timer: null,
      rules: {
        phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
        code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
      },
      positonArr: [],
      slide_bg: "",
      square_url: "",
      login_token: null,
    });
    // 获取验证码
    function getCode() {
      if (!state.ruleForm.phone) return ElNotification.error("请填写手机号");
      state.slide_dialogVisible = true;
      state.blackbox = true;
      get_slide_pic();
    }
    // 倒计时
    function calcTime() {
      state.num = 60;
      state.btn_status = true;
      state.timer = setInterval(function () {
        if (state.num < 1) {
          state.num = "获取验证码";
          clearInterval(state.timer);
          state.btn_status = false;
        } else {
          state.num--;
        }
      }, 1000);
    }
    onMounted(()=>{
      getCredent();
    })
    // 默认获取登陆凭证
    function getCredent(){
       ctx.$http
        .get("/middle/oa/get_login/")
        .then((res) => {
          if (res.errno == 0) {
              localStorage.setItem("credent",res.data.token);
              ElNotification.success(res.errmsg);
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((error) => {
          ElNotification.error(error);
        });
    }
    // 关闭弹窗
    function close_black() {
      state.blackbox = false;
      state.slide_dialogVisible = false;
    }
    // 获取滑块所需图片
    function get_slide_pic() {
      document.getElementById("process").style.width = 0;
      document.getElementById("slideHand").style.left = 0;
      document.getElementById("spanEle1").style.left = 0;
      ctx.$http
        .get("/middle/oa/get_slid_pic/")
        .then((res) => {
          if (res.errno == 0) {
            let IMG_HOST = ctx.$http.IMG_HOST;
            state.slide_bg = IMG_HOST + res.data.bg;
            state.square_url = IMG_HOST + res.data.front;
            state.login_token = res.data.token;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((error) => {
          ElNotification.error(error);
        });
    }
    // 鼠标按住
    function mousedown(e) {
      console.log(e);
      state.ifBool = true;
      state.positonArr = [];
      document.onmousemove = function (eve) {
        if (state.ifBool) {
          let box = document.getElementById("slideDiv"); //滑块图片
          let slideSquare = document.getElementById("slideHand"); //滑手
          let box_outer = box.offsetWidth - 20; //真实宽度-减去左右边距)
          let squre_outer = slideSquare.offsetWidth;
          let l = eve.clientX - box.offsetLeft - squre_outer / 2;
          if (l < 0) {
            l = 0;
          }
          if (l > box_outer - squre_outer) {
            l = box_outer - squre_outer;
          }

          slideSquare.style.left = l + "px";
          document.getElementById("spanEle1").style.left = l + "px";
          document.getElementById("process").style.width = l + "px";
          state.positonArr.push(parseInt(l));
        }
      };
      // 松开鼠标
      document.onmouseup = function () {
        state.ifBool = false;
        document.onmouseover = null;
        document.onmouseup = null;
        if (!state.positonArr.length) return showToast("请移动滑块");
        ctx.$http
          .post("/middle/oa/slid_verify/", {
            token: state.login_token,
            phone: state.ruleForm.phone,
            position: JSON.stringify(state.positonArr),
          })
          .then((res) => {
            if (res.errno == 0) {
              state.blackbox = false;
              state.slide_dialogVisible = false;
              ElNotification.success(res.errmsg);
              calcTime();
            } else {
              get_slide_pic();
              ElNotification.error(res.errmsg);
            }
          })
          .catch((error) => {
            ElNotification.error(error);
          });
      };
    }
    function mouseup() {
      state.ifBool = false;
    }
    // 正式误删
     function submitForm() {
      form.value.validate((valid) => {
        if (valid) {
          ctx.$http
            .post("/middle/oa/login/",
              {
                phone:state.ruleForm.phone,
                code:state.ruleForm.code,
                open_code:state.login_token
              }
            )
            .then((response) => {
              if(response.errno==0){
                ElNotification.success("登陆成功");
                store.state.menu=[];
                // localStorage.setItem("menu", JSON.stringify(response.data.data));
                localStorage.setItem("token", JSON.stringify(response.data.token));
                console.log("token设置完成")
                router.replace("/index");
              }else{
                ElNotification.error(response.errmsg);
              }
            })
            .catch((error) => {
              console.log("error:", error);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
    // function login_opt(){
    //   return new Promise((resolve,reject)=>{

    //   })
    // }
    // 提交
    // function submitForm() {
    //   form.value.validate((valid) => {
    //     console.log(state);
    //     if (valid) {
    //       ctx.$http
    //         .get(
    //           "https://www.fastmock.site/mock/403b6ba32d7466f0039c36115bec6175/auth/usermenu",
    //           {
    //            phone: state.ruleForm.phone,
    //             code: state.ruleForm.code,
    //             open_code:state.login_token || ""
    //           }
    //         )
    //         .then((response) => {
    //           if(response.errno==0){
    //             ElNotification.success("登陆成功");
    //             console.log(response);
    //             localStorage.setItem("menu", JSON.stringify(response.data));
    //             localStorage.setItem("token", 12346);
    //            store.dispatch("addUserMenus",response.data)
    //             // store.commit("setMenu", response.data);
    //             router.push("/");
    //             // initDynamicRoutes();
    //           }else{
    //             ElNotification.error("请将api文件域名去掉");
    //           }
    //         })
    //         .catch((error) => {
    //           console.log("error:", error);
    //         });
    //     } else {
    //       console.log("error submit!!");
    //       return false;
    //     }
    //   });
    // }
    // 切换tab
    function tab(e) {
      state.login_type = e;
    }
    return {
      form,
      submitForm,
      state,
      getCode,
      tab,
      mousedown,
      close_black,
      getCredent
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-box {
    border: 1px solid #dcdfe6;
    width: 350px;
    padding: 10px;
    height: 260px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
    .demo-ruleForm {
      margin-top: 20px;
    }
    .wx_code {
      width: 150px;
      height: 150px;
      border: 1px solid gainsboro;
      display: block;
      margin: auto;
      margin-top: 20px;
    }
    .getCode_btn {
      width: 112px;
    }
    .active {
      color: #3682cc;
    }
    .item {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
    }
  }

  .login-title {
    text-align: center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
  .slideDiv {
    z-index: 12001;
    width: 320px;
    height: 220px;
    padding: 10px;
    border-radius: 8px;
    box-sizing: border-box;
    position: fixed;
    left: calc(50% - 160px);
    top: calc(50% - 105px);
    background: #f2ece1;
  }
  .refreshBtn {
    width: 26px;
    height: 26px;
    left: 0;
    bottom: 0;
    position: absolute;
    z-index: 11111;
    cursor: pointer;
    font-size: 26px;
  }
  .closeSlide {
    font-size: 20px;
    font-weight: bold;
    position: absolute;
    z-index: 111111111;
    right: -16px;
    top: -16px;
    display: flex;
    align-items: center;
    width: 30px;
    height: 30px;
    justify-content: center;
    border-radius: 50%;
    background: #f2ece1;
    color: red;
    cursor: pointer;
  }

  .box {
    width: 300px;
    height: 150px;
    margin: 0 auto;
    position: relative;
    background: #fff;
  }

  .box .main1 {
    width: 100%;
    height: 100%;
    display: block;
    border-radius: 4px;
  }

  .btn {
    width: 300px;
    height: 38px;
    margin: 10px auto;
    position: relative;
    display: flex;
    align-items: center;
    border: 1px solid #c3c3c3;
    background: #ece4dd;
    justify-content: center;
    color: #45494c;
    box-shadow: 0 1px 1px rgba(12, 10, 10, 0.2) inset;
  }

  .process {
    height: 38px;
    position: absolute;
    left: 0;
    top: 0;
    background: #7d7d7d;
  }

  .slideSquare {
    user-select: none;
    width: 38px;
    height: 38px;
    position: absolute;
    left: 0px;
    top:0;
    background: #383535;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #88c86b;
    opacity: 0.9;
    font-size: 28px;
    z-index: 1111111111111;
  }

  .slideSquare:hover {
    background: #000000;
    opacity: 1;
  }

  .spanEle1 {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 222;
    width: 35px;
    height: 35px;
    box-sizing: border-box;
  }
  .black-box {
    z-index: 800;
    top: 0;
    left: 0;
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: black;
    opacity: 0.3;
  }
}
</style>